<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../../css/mui.css" rel="stylesheet" />
		<link href="../../css/header.css" rel="stylesheet" />
		<style>
			html,
			body {
				height: 100%;
			}
			
			.mui-content {
				height: 100%;
				overflow: auto;
			}
			
			.red-point{
		      position: relative;
		    }
			
		    .red-point::before{
		      content: " ";
		      border: 5px solid #C9394A;/*设置红色*/
		      border-radius:5px;/*设置圆角*/
		      position: absolute;
		      z-index: 3000;
		      right: 0%;
		      margin-right: -10px;
		      margin-top: 0px;
		    }
			.head-img{
				border-radius: 5px;
			}
			
			.unread-red-point{
				width: 14px;
				height: 14px;
				border-radius: 7px;
				background-color: red;
				color: white;
				line-height: 14px; 
				text-align: center; 
				font-size: 8px; 
				position: absolute;
				left: 49px;
				top: 5px;
				z-index: 999;
			}
			
			.unread-red-point-hidden{
				display: none;
			}
		</style>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav title">
			<span class="mui-action-back nav mui-pull-left title-color" style="line-height: 44px; margin-left: 5px;">微信</span>
		</header>
		<div class="mui-content">
			<ul id="ul_friend_request_list" class="mui-table-view" style="margin: 0;">

			</ul>
			<ul id="ul_chatSnapshot" class="mui-table-view">
				<!-- <li friendUserId="" friendNickname="" snapshotId="" friendThumHeadPortrait="" class="chat-with-friend mui-table-view-cell mui-media">
					<div class="mui-slider-right mui-disabled">
						<a friendUserId="" class="mui-btn mui-btn-red btn-delete">删除</a>
					</div>
					<div class="unread-red-point">10</div>
					<div class="mui-slider-handle mui-media-body ">
						<img class="mui-media-object mui-pull-left head-img" src="../../image/head/default_head-1.jpg" />
						<label style="font-size: 16px;">小花</label>
						<p class="mui-ellipsis">一条信息</p>
					</div>
				</li> -->
			</ul>
		</div>
		<script src="../../js/mui.js"></script>
		<script src="../../js/app.js"></script>
		<script src="../../js/api/friendapi.js"></script>
		<script src="../../js/api/chatapi.js"></script>
		<script src="../../js/db/db.js"></script>
		<script src="../../js/db/dictionariesdb.js"></script>
		<script src="../../js/db/chatmessagedb.js"></script>
		<script src="../../js/db/chatsnapshotmessagedb.js"></script>
		<script src="../../js/db/frienddb.js"></script>
		<script type="text/javascript">
			mui.init();

			mui.plusReady(function() {
				// 获取登录用户
				let user = app.getCacheUser();
				// 获取当前页面
				let currentWebview = plus.webview.currentWebview();
				currentWebview.addEventListener("show", function() {
					// 加载好友请求记录
					requestFriendRequests(() => {
						// 为请求添加的好友头像批量绑定点击事件
						requestHeadBindEvent()
					});
					// 获取消息记录
					chatapi.getUnreadMessageList({
						userId: user.id
					});
					// 加载聊天快照
					loadingChatSnapshot(() => {
						liBindEvent(); // 为聊天快照列表量绑定点击事件
						headBindEvent(); // 为好友头像批量绑定点击事件
					});
				});
				// 添加自定义事件，刷新好友请求，初始化websocket
				window.addEventListener("refresh", function() {
					console.log("refresh -> refresh") // 加载好友请求记录
					requestFriendRequests(() => {
						// 为请求添加的好友头像批量绑定点击事件
						requestHeadBindEvent()
					});
				});

				/**
				 * 为聊天快照列表量绑定点击事件
				 */
				function liBindEvent() {
					mui("#ul_chatSnapshot").on("tap", ".chat-with-friend", function(e) {
						let friendUserId = this.getAttribute("friendUserId");
						let friendNickname = this.getAttribute("friendNickname");
						let friendThumHeadPortrait = this.getAttribute("friendThumHeadPortrait");
						let friendAccount = this.getAttribute("friendAccount");

						// 页面参数选项
						let option = {
							url: "chatting.html",
							id: "chatting-" + friendUserId, // 每个朋友的聊天页面都是唯一对应的
							extras: {
								friendUserId: friendUserId,
								friendNickname: friendNickname,
								friendThumHeadPortrait: friendThumHeadPortrait,
								friendAccount: friendAccount
							}
						};

						let snapshotId = this.getAttribute('snapshotId');
						// 打开聊天界面
						openChattingView(snapshotId, option);
					});
				}


				/**
				 * 为好友头像批量绑定点击事件
				 */
				function headBindEvent() {
					mui("#ul_chatSnapshot").on("tap", ".head-img", function(e) {
						e.stopPropagation();
						var account = this.getAttribute("account");
						openFriendDetailView(account);
					})
				}

				/**
				 * 为请求添加的好友头像批量绑定点击事件
				 */
				function requestHeadBindEvent() {
					mui("#ul_friend_request_list").on("tap", ".head-img", function(e) {
						var account = this.getAttribute("account");
						openFriendDetailView(account);
					})
				}

				/**
				 * 打开好友详情页面
				 * @param {Object} account 好友账号
				 */
				function openFriendDetailView(account) {
					friendapi.getFriendByAccount({
						userId: app.getUserId(),
						account: account
					}, (data) => {
						frienddb.updateExcute(data.word, data, () => {
							// 打开聊天子页面
							mui.openWindow({
								url: "../discover/friend-detail.html",
								id: 'friend-detail.html', // 每个朋友的聊天页面都是唯一对应的
								extras: {
									requestFriend: {
										id: data.id,
										account: data.account,
										nickname: data.nickname,
										thumHeadPortrait: data.thumHeadPortrait,
										address: data.address,
										span_signature: data.signature,
										isFriend: true
									}
								}
							});
						})
					})
				}

				/**
				 * 打开聊天界面
				 * @param {Object} snapshotId 快照id
				 * @param {Object} option 页面参数选项
				 */
				function openChattingView(snapshotId, option) {
					console.log(snapshotId)
					// 查询聊天快照记录
					chatsnapshotmessagedb.select({
						id: snapshotId,
						userId: app.getUserId()
					}, (data) => {
						if (data.length > 0 && data[0].unread != 0) {
							// 标记未读状态为已读
							updateMessageIsRead({
								friendId: data[0].friend_id,
								snapshotId: snapshotId
							}, () => {
								// 打开聊天子页面
								mui.openWindow(option);
							})
						} else {
							// 打开聊天子页面
							mui.openWindow(option);
						}
					})
				}

				/**
				 * 标记聊天信息已读，将快照未读消息条数修改为0
				 * @param {Object} params1 {friendId, snapshotId}，好友id和快照id
				 * @param {Object} call 回调函数
				 */
				function updateMessageIsRead(params1, call) {
					let userId = app.getUserId();
					let friendId = params1.friendId;
					let snapshotId = params1.snapshotId;
					// 标记未读状态为已读
					chatsnapshotmessagedb.updateUnread({
						id: snapshotId,
						unread: 0
					}, () => {
						let params2 = {
							userId: userId,
							friendId: friendId,
							status: 0
						};
						chatmessagedb.updateStatus(params2, () => {
							// 渲染快照列表进行展示
							loadingChatSnapshot(() => {
								if (typeof call === 'function') {
									call();
								}
							});
						})
					});
				}

				// 左滑删除聊天快照和记录
				mui("#ul_chatSnapshot").on("tap", ".btn-delete", function(e) {
					const _this = this; // a 标签
					let btnArray = ['取消', '删除'];
					mui.confirm('删除后，将清空该聊天的消息记录', ' ', btnArray, function(e) {
						if (e.index == 1) {
							// 获取朋友id
							let friendUserId = _this.getAttribute("friendUserId");
							// 1. 删除本地聊天记录
							let params = {
								userId: user.id,
								friendId: friendUserId
							}
							chatmessagedb.deleteByMapping(params)
							// 2. 删除本地聊天快照
							chatsnapshotmessagedb.deleteByMapping(params);
							// 3. 移除当前用户操作的dom节点
							let li = _this.parentNode.parentNode; // 获取li标签
							let ul_chatSnapshot = document.getElementById("ul_chatSnapshot");
							ul_chatSnapshot.removeChild(li); // 删除li标签
						}
					}, "div");
				});

			});

			// 后台获取好友发送的未读消息
			function requestFriendRequests(call) {
				friendapi.getFriendRequests((friendsRequestList) => {
					let ul_friend_request_list = document.getElementById("ul_friend_request_list");
					if (friendsRequestList != null && friendsRequestList.length > 0) {
						let requestHtml = "";
						for (let i = 0; i < friendsRequestList.length; i++) {
							requestHtml += createFriendRequestsHtml(friendsRequestList[i]);
						}
						ul_friend_request_list.innerHTML = requestHtml;
						bindBtnEvent();
						if (typeof call === 'function') {
							call();
						}
					} else {
						ul_friend_request_list.innerHTML = "";
					}
				});
			}


			// 创建好友请求html
			function createFriendRequestsHtml(fr) {
				// let html = "";
				let imgUrl = '../../image/loading.jpg';
				if (fr.thumHeadPortrait) {
					imgUrl = fr.thumHeadPortrait;
				}
				return `
						<li class="btnOper mui-table-view-cell mui-media">
							<a href="javascript:;">
								<img class="mui-media-object mui-pull-left head-img" account="${fr.account}" src="${imgUrl}" />
								<span id="span_nickname" class="mui-pull-right"> 
									<button friendsRequestId="${fr.friendsRequestId}" type="button" class="ignoreRequest mui-btn mui-btn-grey" style="padding: 4px 10px;margin-right:5px;">忽略</button> 
									<button friendsRequestId="${fr.friendsRequestId}" type="button" class="passRequest mui-btn mui-btn-danger" style="padding: 4px 10px;">通过</button> 
								</span>
								<div class="mui-media-body">
									<label>${fr.nickname}</label>
									<p class="mui-ellipsis">请求添加你为朋友</p>
								</div>
							</a>
						</li>
						`;
			}

			// 绑定按钮tap事件
			function bindBtnEvent() {
				// 绑定忽略事件
				mui(".btnOper").on("tap", ".ignoreRequest", function(e) {
					let friendsRequestId = this.getAttribute("friendsRequestId");
					operatorFriendRequest(friendsRequestId, -1);
				});
				// 绑定同意事件
				mui(".btnOper").on("tap", ".passRequest", function(e) {
					let friendsRequestId = this.getAttribute("friendsRequestId");
					operatorFriendRequest(friendsRequestId, 1);
				});
			}

			// 忽略/同意好友请求
			function operatorFriendRequest(friendsRequestId, status) {
				let user = app.getCacheUser();
				let params = {
					userId: user.id,
					friendsRequestId: friendsRequestId,
					status: status
				}
				console.log(JSON.stringify(params));
				friendapi.operatorFriendRequest(params, (res) => {
					if (status == 1 && res.code == 0) {
						// 更新通讯录
						let friend = res.data;
						frienddb.insertExcute(friend.word, friend);
						// 重新加载好友请求记录
						requestFriendRequests();
					}
				})
			}

			// 展示聊天快照，渲染列表
			function loadingChatSnapshot(call) {
				console.log(app.formatDate(new Date()) + ': [info]' + ' ======> [渲染聊天快照]');
				let user = app.getCacheUser();
				chatsnapshotmessagedb.select({
					userId: user.id
				}, (chatSnapshotList) => {
					// console.log(JSON.stringify(chatSnapshotList));
					let ul_chatSnapshot = document.getElementById("ul_chatSnapshot");
					ul_chatSnapshot.innerHTML = "";
					if (chatSnapshotList == null || chatSnapshotList.length == 0) {
						return;
					}
					for (let snapshot of chatSnapshotList) {
						let template =
							`
						<li class="chat-with-friend mui-table-view-cell mui-media" friendUserId="${snapshot.friend_id}" friendNickname="${snapshot.nickname}" snapshotId="${snapshot.id}" friendThumHeadPortrait="${snapshot.thum_head_portrait}" friendAccount="${snapshot.account}">
							<div class="mui-slider-right mui-disabled">
								<a class="mui-btn mui-btn-red btn-delete" friendUserId="${snapshot.friend_id}">删除</a>
							</div>
							<div class="unread-red-point ${snapshot.unread==0 ? "unread-red-point-hidden" : ""}">${snapshot.unread}</div>
							<div class="mui-slider-handle mui-media-body ">
								<img class="mui-media-object mui-pull-left head-img" account="${snapshot.account}" src="${snapshot.thum_head_portrait}" />
								<label style="font-size: 16px;">${snapshot.nickname}</label>
								<p class="mui-ellipsis">${snapshot.message}</p>
							</div>
						</li>
						`
						ul_chatSnapshot.insertAdjacentHTML('beforeend', template);
					}
					if (typeof call === 'function') {
						call();
					}
					//关闭等待框
					plus.nativeUI.closeWaiting();
				})
			}
		</script>
	</body>

</html>
